package com.icen.utils.comm;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Display;
import android.view.WindowManager;

/**
 * Image Utils Class
 * 
 * @author IcenHan
 * 
 */
public class ImageUtils {
	/**
	 * 将图片转化为Bitmap格式
	 * 
	 * @param imgPath
	 *            图片文件路径
	 * @return Bitmap
	 */
	public static Bitmap imgToBitmap(String imgPath) {
		try {
			FileInputStream fis = new FileInputStream(imgPath);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * byte --> bitmap
	 * 
	 * @param b
	 * @return Bitmap
	 */
	public static Bitmap byteToBitmap(byte[] b) {
		return (b == null || b.length == 0) ? null : BitmapFactory
				.decodeByteArray(b, 0, b.length);
	}

	/**
	 * byte --> drawable
	 * 
	 * @param b
	 * @return Drawable
	 */
	public static Drawable byteToDrawable(byte[] b) {
		return bitmapToDrawable(byteToBitmap(b));
	}

	/**
	 * bitmap --> byte
	 * 
	 * @param bitmap
	 * @return byte[]
	 */
	public static byte[] bitmapToByte(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}

		ByteArrayOutputStream o = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, o);
		return o.toByteArray();
	}

	/**
	 * bitmap --> Drawable
	 * 
	 * @param bitmap
	 * @return Drawable
	 */
	@SuppressWarnings("deprecation")
	public static Drawable bitmapToDrawable(Bitmap bitmap) {
		return bitmap == null ? null : new BitmapDrawable(bitmap);
	}

	/**
	 * Drawable --> bitmap
	 * 
	 * @param d
	 * @return Bitmap
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		return drawable == null ? null : ((BitmapDrawable) drawable)
				.getBitmap();
	}

	/**
	 * drawable --> byte
	 * 
	 * @param drawable
	 * @return byte[]
	 */
	public static byte[] drawableToByte(Drawable drawable) {
		return bitmapToByte(drawableToBitmap(drawable));
	}

	/**
	 * 将Bitmap类型的图片保存为指定类型的图片
	 * 
	 * @param bitmap
	 *            Bitmap文件
	 * @param filePath
	 *            文件保存路径(包括文件名)
	 * @param fileExs
	 *            文件扩展名
	 * @return boolean
	 */
	public static boolean saveBitmap(Bitmap bitmap, String filePath,
			String fileExs) {
		// 创建文件
		File file = new File(filePath + fileExs);
		// 同名文件存在,删除
		if (file.exists()) {
			file.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 将Bitmap类型的图片保存为JPG类型的图片
	 * 
	 * @param bitmap
	 *            Bitmap文件
	 * @param filePath
	 *            文件保存路径(包括文件名)
	 * @return boolean
	 */
	public static boolean saveBitmapToJpg(Bitmap bitmap, String filePath) {
		return ImageUtils.saveBitmap(bitmap, filePath, ".jpg");
	}

	/**
	 * 将Bitmap类型的图片保存为PNG类型的图片
	 * 
	 * @param bitmap
	 *            Bitmap文件
	 * @param filePath
	 *            文件保存路径(包括文件名)
	 * @return boolean
	 */
	public static boolean saveBitmapToPng(Bitmap bitmap, String filePath) {
		return ImageUtils.saveBitmap(bitmap, filePath, ".png");
	}

	/**
	 * 获取自适应屏幕大小的图片
	 * 
	 * @param drawable
	 * @return Bitmap
	 */
	public static Bitmap getResizedBitmap(Context context,
			BitmapDrawable drawable) {
		Bitmap bitmap = drawable.getBitmap();
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		@SuppressWarnings("deprecation")
		int height = display.getHeight();
		@SuppressWarnings("deprecation")
		int width = display.getWidth();
		if (height < 480 || width < 320) {
			return Bitmap.createScaledBitmap(bitmap, 32, 32, false);
		} else {
			return Bitmap.createScaledBitmap(bitmap, 48, 48, false);
		}
	}

	/**
	 * 转换为圆角图片
	 * 
	 * @param bitmap
	 *            需要修改的图片
	 * @param pixels
	 *            圆角的弧度
	 * @return Bitmap
	 */
	public static Bitmap getRoundCornerBitmap(Bitmap bitmap, int pixels) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 转换为圆角图片,支持BitampDrawable
	 * 
	 * @param bitmapDrawable
	 * @param pixels
	 * @return BitmapDrawable
	 */
	@SuppressWarnings("deprecation")
	public static BitmapDrawable getRoundCornerBitmapDraw(
			BitmapDrawable bitmapDrawable, int pixels) {
		Bitmap bitmap = bitmapDrawable.getBitmap();
		bitmapDrawable = new BitmapDrawable(
				getRoundCornerBitmap(bitmap, pixels));
		return bitmapDrawable;
	}

	/**
	 * 生成图片倒影
	 * 
	 * @param originalImage
	 * @return Bitmap
	 */
	public static Bitmap createReflectedImage(Bitmap originalImage) {
		final int reflectionGap = 4;
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();
		Matrix matrix = new Matrix();

		matrix.preScale(1, -1);
		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
				height / 2, width, height / 2, matrix, false);
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(originalImage, 0, 0, null);

		Paint defaultPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0,
				originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
						+ reflectionGap, 0x70ffffff, 0x00ffffff,
				TileMode.MIRROR);
		paint.setShader(shader);
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);

		return bitmapWithReflection;
	}

	private static float[] carray = new float[20];

	/**
	 * 图片去色,返回灰度图片
	 * 
	 * @param bmpOriginal
	 *            传入的图片
	 * @return 去色后的图片
	 */
	public static Bitmap getGrayBitmap(Bitmap bmpOriginal) {

		int width, height;
		height = bmpOriginal.getHeight();
		width = bmpOriginal.getWidth();
		Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,
				Bitmap.Config.RGB_565);
		Canvas c = new Canvas(bmpGrayscale);
		Paint paint = new Paint();
		paint.setColorFilter(null);
		c.drawBitmap(bmpGrayscale, 0, 0, paint);
		ColorMatrix cm = new ColorMatrix();
		getValueBlackAndWhite();
		cm.set(carray);
		ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
		paint.setColorFilter(f);
		c.drawBitmap(bmpOriginal, 0, 0, paint);
		return bmpGrayscale;
	}

	/**
	 * 去色同时加圆角
	 * 
	 * @param bmpOriginal
	 *            原图
	 * @param pixels
	 *            圆角弧度
	 * @return Bitmap
	 */
	public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
		return getRoundCornerBitmap(getGrayBitmap(bmpOriginal), pixels);
	}

	private static void getValueBlackAndWhite() {
		// 黑白
		carray[0] = (float) 0.308;
		carray[1] = (float) 0.609;
		carray[2] = (float) 0.082;
		carray[3] = 0;
		carray[4] = 0;
		carray[5] = (float) 0.308;
		carray[6] = (float) 0.609;
		carray[7] = (float) 0.082;
		carray[8] = 0;
		carray[9] = 0;
		carray[10] = (float) 0.308;
		carray[11] = (float) 0.609;
		carray[12] = (float) 0.082;
		carray[13] = 0;
		carray[14] = 0;
		carray[15] = 0;
		carray[16] = 0;
		carray[17] = 0;
		carray[18] = 1;
		carray[19] = 0;
	}
}
